package com.resouxs.free_book.api;

import android.annotation.SuppressLint;
import android.support.annotation.NonNull;
import android.util.Log;

import com.resouxs.free_book.service.ApiImp;
import com.resouxs.free_book.service.BookSource;
import com.resouxs.free_book.service.SimilarityUtils;
import com.resouxs.free_book.service.ZSChapterContentService;
import com.resouxs.free_book.service.ZhuishuService;
import com.resouxs.free_book.service.ZsBookChapter;
import com.resouxs.free_book.service.ZsBookChapterContent;
import com.resouxs.free_book.service.ZsChapter;

import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class ZsFBook implements IFBook<ZsFBookCallback, ZsChapterCallback> {

    private CyclicBarrier barrier;

    public void setLocker(CyclicBarrier barrier)
    {
        this.barrier = barrier;
    }

    @Override
    public void getBookChapterContent(String bookLink,  ZsFBookCallback zsFBookCallback) {
        getBookContent(bookLink, zsFBookCallback);
    }

    @SuppressLint("CheckResult")
    @Override
    public void getBookChapters(String bookId, @NonNull final String latestChapter, final ZsChapterCallback zsChapterCallback) {

        if(bookId == null)
        {
            zsChapterCallback.onGetChaptersFailed("bookId cannot be null");
            return;
        }

        final ZhuishuService zhuishuService = ApiImp.getInstance().getService(ZhuishuService.class);
        Observable<List<BookSource>> bookSource = zhuishuService.getBookSource(bookId);
        bookSource.subscribeOn(Schedulers.io())
                .flatMap(new Function<List<BookSource>, ObservableSource<ZsBookChapter>>() {
                    @Override
                    public ObservableSource<ZsBookChapter> apply(List<BookSource> bookSources) throws Exception {
                        ObservableSource<ZsBookChapter> zsBookChapterObservableSource = getZsBookChapterObservableSource(bookSources, latestChapter, zhuishuService);
                        if(barrier != null)
                        {
                            try {
                                barrier.await(3, TimeUnit.SECONDS);//等待获取所有的章节列表
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            } catch (BrokenBarrierException e) {
                                e.printStackTrace();
                            }
                        }
                        return zsBookChapterObservableSource;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ZsBookChapter>() {
                    @Override
                    public void accept(ZsBookChapter zsBookChapter) throws Exception {
//                        if(zsBookChapter.getSource().equals("biquge"))
//                        {
//                            List<ZsChapter> chapters = zsBookChapter.getChapters();
//                            List<ZsChapter> zsChapters = chapters.subList(12, chapters.size() - 1);
//                            zsBookChapter.setChapters(zsChapters);
//                        }
                        zsChapterCallback.onGetChapters(zsBookChapter);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        System.out.println("getBookChapter error"+throwable.getMessage());
                        zsChapterCallback.onGetChaptersFailed("getBookChapter error: "+throwable.getMessage());
                    }
                });
    }

    private ObservableSource<ZsBookChapter> getZsBookChapterObservableSource(List<BookSource> bookSources, String latestChapter, ZhuishuService zhuishuService) {
        //定义最大相似度变量
        float maxSmilarity = 0;
        String sourceId = null;
        String my716SourceId = null;
        for(BookSource bookSource : bookSources)
        {
            String source = bookSource.getSource();
            if(source == null) continue;

            if(source.contains("vip")) continue;
            if(source.contains("my176"))
            {
                my716SourceId = bookSource.get_id();
            }

//            if(latestChapter != null) {
//                float similarity = SimilarityUtils.levenshtein(subChapterName(bookSource.getLastChapter()).trim(), subChapterName(latestChapter).trim());
//                if(similarity > maxSmilarity)
//                {
//                    maxSmilarity = similarity;
//                    sourceId = bookSource.get_id();
//                }
//            }
        }
		if(my716SourceId != null)
        {
            sourceId = my716SourceId;
        }
        else if(maxSmilarity < 0.3 && bookSources.size() > 1)
        {
            sourceId = bookSources.get(1).get_id();
        }
        if(sourceId == null)
        {
            return null;
        }
        return zhuishuService.getBookChapter(sourceId, "chapters");
    }

    @SuppressLint("CheckResult")
    private void getBookContent(final String bookLink, final ZsFBookCallback zsFBookCallback)
    {
        ZSChapterContentService chContentService = ApiImp.getInstance().getChContentService(ZSChapterContentService.class);
        chContentService.getChapterContent(bookLink)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ZsBookChapterContent>() {
                               @Override
                               public void accept(ZsBookChapterContent zsBookChapterContent) throws Exception {
                                   zsFBookCallback.onSuccess(zsBookChapterContent);

                               }
                           }, new Consumer<Throwable>() {
                               @Override
                               public void accept(Throwable throwable) throws Exception {
                                   zsFBookCallback.onFailed("error: "+throwable.getMessage());
                               }
                           }
                );
    }

//    private static String subChapterName(String chapterTitle) {
//        if( chapterTitle.contains("章")) {
//            chapterTitle = chapterTitle.replaceFirst("(.*)章(\\s)","").replaceAll("\\s{1,}", "");
//        }
//        return chapterTitle;
//    }
}
